/**
 * 
 */
package activity;

import static activity.ActivityParameters.ALTITUDE;
import static activity.ActivityParameters.DESCRIPTION;
import static activity.ActivityParameters.END_TIME;
import static activity.ActivityParameters.ID;
import static activity.ActivityParameters.LATITUDE;
import static activity.ActivityParameters.LONGITUDE;
import static activity.ActivityParameters.METHOD;
import static activity.ActivityParameters.START_TIME;
import static activity.ActivityParameters.TITLE;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import location.ECEFCoordinates;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import persistence.ActivityEntity;

import com.google.gson.Gson;

import error.ErrorMessage;

/**
 * CRUD operations for Activities. {@link http
 * ://stackoverflow.com/questions/1051004
 * /how-to-send-put-delete-http-request-in-
 * httpurlconnection-looks-like-not-workin} {@link http
 * ://sites.google.com/site/gson/gson-user-guide}
 * 
 * @author Stefan
 * 
 */
public class ActivityServlet extends HttpServlet {
	private static final Log log = LogFactory.getLog(ActivityServlet.class);
	private static Gson gson = new Gson();

	/**
	 * create an Activity.
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if ((req.getParameter(LATITUDE) == null)
				|| (req.getParameter(LONGITUDE) == null)
				|| (req.getParameter("alt") == null)
				|| (req.getParameter(START_TIME) == null)
				|| (req.getParameter(END_TIME) == null)
				|| (req.getParameter(DESCRIPTION) == null)
				|| (req.getParameter("title") == null)) {
			resp
					.getWriter()
					.write(
							gson
									.toJson(new ErrorMessage(
											"Invalid CreateActivity request. Check Parameters.")));
		} else {
			Activity newActivity = ActivityEntity.newInstance("ACY"
					+ System.currentTimeMillis());
			ECEFCoordinates ecef = new ECEFCoordinates(req.getParameter(LATITUDE),
					req.getParameter(LONGITUDE), req.getParameter(ALTITUDE));
			// set parameters of activity
			newActivity.setDescription(req.getParameter(DESCRIPTION));
			newActivity.setStartTime(Long.parseLong(req
					.getParameter(START_TIME)));
			newActivity.setEndTime(Long.parseLong(req.getParameter(END_TIME)));
			newActivity.setTitle(req.getParameter(TITLE));
			
			newActivity.setLatitude(Double.parseDouble(req.getParameter(LATITUDE)));
			newActivity.setLongitude(Double.parseDouble(req.getParameter(LONGITUDE)));
			newActivity.setAltitude(Double.parseDouble(req.getParameter(ALTITUDE)));
			newActivity.setX(ecef.getX());
			newActivity.setY(ecef.getY());
			newActivity.setZ(ecef.getZ());
			
			// respond activity json object
			
			resp.getWriter().write(gson.toJson(newActivity, ActivityEntity.class).toString()
					);
		}

	};

	/**
	 * read an Activity. TODO needed?
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter(METHOD);
		if (method != null) {
			if (method.equals("post")) {
				doPost(req, resp);
				return;
			}
			if (method.equals("put")) {
				doPut(req, resp);
				return;
			}
			if (method.equals("delete")) {
				doDelete(req, resp);
				return;
			}
		}

		// forwardRequestParameters(req, resp);
		String id = req.getParameter(ID);
		log.trace("doGet " + id);
		if (id == null) {
			resp.getWriter().write(
					gson.toJson(new ErrorMessage("No id specified")));
		} else {
			Activity activity = ActivityEntity.getInstance(id, true);

			if (null != activity) {
				resp.getWriter().write(
						gson.toJson(activity, ActivityEntity.class).toString());
			} else {
				resp.getWriter().write(
						gson.toJson(new ErrorMessage("No such activity: " + id
								+ "")));
			}

		}
	}

	/**
	 * modify an Activity.
	 */
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String id = req.getParameter(ID);
		log.trace("doGet " + id);
		if (id == null) {
			resp.getWriter().write(
					gson.toJson(new ErrorMessage("No id specified")));
			return;
		} else {
			Activity activity = ActivityEntity.getInstance(id, true);
			if (null != activity) { // update parameters that are set

				if ((req.getParameter(LATITUDE) != null)
						&& (req.getParameter(LONGITUDE) != null)
						&& (req.getParameter(ALTITUDE) != null)) {
					ECEFCoordinates ecef = new ECEFCoordinates(req
							.getParameter(LATITUDE), req
							.getParameter(LONGITUDE), req
							.getParameter(ALTITUDE));
					activity.setX(ecef.getX());
					activity.setY(ecef.getY());
					activity.setZ(ecef.getZ());
					activity.setLatitude(Double.parseDouble(req.getParameter(LATITUDE)));
					activity.setLongitude(Double.parseDouble(req.getParameter(LONGITUDE)));
					activity.setAltitude(Double.parseDouble(req.getParameter(ALTITUDE)));
				}
				if (req.getParameter(TITLE) != null)
					activity.setTitle(req.getParameter(TITLE));

				if (req.getParameter(START_TIME) != null)
					activity.setStartTime(Long.parseLong(req
							.getParameter(START_TIME)));
				if (req.getParameter(END_TIME) != null)
					activity.setEndTime(Long.parseLong(req
							.getParameter(END_TIME)));
				if (req.getParameter(DESCRIPTION) != null)
					activity.setDescription(req.getParameter(DESCRIPTION));

				// respond updated activity json object
				resp.getWriter().write(
						gson.toJson(activity, ActivityEntity.class).toString());

			} else {
				resp.getWriter().write(
						gson.toJson(new ErrorMessage("No such activity: " + id
								+ "")));
				return;
			}

		}
	}

	/**
	 * delete an Activity.
	 */
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String id = req.getParameter(ID);
		log.trace("doDelete " + id);
		if (id == null) {
			resp.getWriter().write(
					gson.toJson(new ErrorMessage("No id specified"))) ;
		} else {
			ActivityEntity.removeInstance(id);
			resp.getWriter().write("true");
		}
	};

}
